package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource("classpath:/properties/image.properties")
public class FIleServiceImpl implements FIleService {
    @Value("${image.localDir}")
    private String localDir;
    @Value("${image.urlName}")
    private String urlName;

    private static Set<String> sets=new HashSet<>();
    static {
        sets.add(".png");
        sets.add(".jpg");
        sets.add(".gif");
    }

    @Override
    public ImageVO upload(MultipartFile uploadFile) {
        String fileName=uploadFile.getOriginalFilename();
        fileName=fileName.toLowerCase();

        String fileType=fileName.substring(fileName.lastIndexOf("."));
        if (!sets.contains(fileType)){
            return ImageVO.fail();
        }
        try {
            BufferedImage bufferedImage= ImageIO.read(uploadFile.getInputStream());
            int width=bufferedImage.getWidth();
            int height=bufferedImage.getHeight();
            if (width==0||height==0){
                return ImageVO.fail();
            }
            String dateDir=new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

            String dirPath=localDir+dateDir;
            File dirFile=new File(dirPath);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            String uuid= UUID.randomUUID().toString().replace("-", "_");

//            uuid: 12_dsds_123 fileType:.jpg  realFileName:13132_.jpg
            String realFileName=uuid+fileType;

            uploadFile.transferTo(new File(dirPath+realFileName));

            String url=urlName+dateDir+realFileName;
            return ImageVO.success(url, width, height);

        }catch (IOException e){
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
